<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 搜索添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getUserList"></el-button>
            </template>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column prop="mg_state" label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeswitch(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="操作" label="操作">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editusers(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :hide-after="0"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="roleUsers(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户弹出框 -->
      <el-dialog
        :visible.sync="addDialogVisible"
        title="添加用户"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form
          ref="addFormRef"
          label-width="70px"
          :model="addForm"
          :rules="addFormRulse"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile" class="lastitem">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改用户信息 -->
      <el-dialog
        :visible.sync="editDialogVisible"
        title="修改用户信息"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form
          ref="editFormRef"
          label-width="70px"
          :model="editForm"
          :rules="addFormRulse"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile" class="lastitem">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="editUser">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除用户 -->

      <!-- 分配角色 -->
      <el-dialog
        :visible.sync="rolesDialogVisible"
        title="分配角色"
        width="50%"
        @close="closeRole"
      >
        <!-- 内容主体区 -->
        <!-- selectedRoleId是双向绑定后的值也就是选定的：value的值，存到selectedRoleId里 -->
        <div>
          <p>当前的用户：{{ roleInfo.username }}</p>
          <p>当前的角色：{{ roleInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button>取消</el-button>
            <el-button type="primary" @click="saveRoleInfo">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { MessageBox,Message } from "element-ui";

export default {
  name: "Users",
  data() {
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
      if (regEmail.test(value)) callback();
      callback(new Error("请输入合法邮箱"));
    };
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|7|8)\d{9}$/;
      if (regMobile.test(value)) callback();
      callback(new Error("请输入合法手机号"));
    };
    return {
      rolesDialogVisible: false,
      // 需要被分配的角色用户信息
      roleInfo: {},
      // 所有角色用户列表
      rolesList: [],
      // 获取用户列表的参数对象
      selectedRoleId: "",
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: "ljr",
        password: "111111",
        email: "3507493195@qq.com",
        mobile: "17711791597",
      },
      addFormRulse: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在3到10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6到15个字符", trigger: "blur" },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机",
            trigger: "blur",
          },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editForm: {},
      editFormRulse: {},
    };
  },
  created() {
    this.getUserList();
  },
  components: {},
  methods: {
    // 发起请求获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("/users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听页码内容大小改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    // 监听页面改变
    handleCurrentChange(newnum) {
      this.queryInfo.pagenum = newnum;
      this.getUserList();
    },
    // 更新用户状态
    async changeswitch(userInfo) {
      console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        // 如果更新状态失败,要先把 userInfo.mg_state 取反
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新状态失败");
      }
      return this.$message.success("更新状态成功");
    },
    // 关闭弹出框重置添加用户表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击确定按钮,添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // 如果验证失败之间return空
        if (!valid) return;
        // 如果验证成功就发起请求添加用户
        const { data: res } = await this.$http.post("/users", this.addForm);
        if (res.meta.status == 400) {
          return this.$message.error("添加用户失败,用户名存在");
        } else if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败,请重试");
        }
        this.$message.success("添加用户成功");
        // 影藏弹出框
        this.addDialogVisible = false;
        // 重新获取用户列表
        this.getUserList();
      });
    },
    // 点击弹出修改用户信息框
    async editusers(id) {
      // 根据 ID 查询用户信息
      const { data: res } = await this.$http.get("/users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 点击验证修改用户信息表并发送请求
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        // 如果验证失败之间return空
        if (!valid) return;
        // 如果验证成功就发起请求用户
        const { data: res } = await this.$http.put(
          "/users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改用户失败,请重试");
        }
        this.$message.success("修改用户成功");
        // 影藏弹出框
        this.editDialogVisible = false;
        // 重新获取用户列表
        this.getUserList();
      });
    },
    // 取消修改按钮,重置修改表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 删除用户
    async deleteUser(id) {
      const res = await MessageBox.confirm(
        "此操作将永久删除该用户,是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        Message({
          type: "info",
          message: "已取消删除",
        });
      });
      // 如果用户确认了删除,返回字符串confirm
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("/users/" + id);
        if (res.meta.status !== 200) return this.$message.error("删除用户失败");
        Message({
          type: "success",
          message: "删除用户成功",
        });
        this.getUserList();
      }
    },
    // 点击分配角色，弹出弹框q
    async roleUsers(roles) {
      this.roleInfo = roles;
      this.rolesDialogVisible = true;
      // console.log(roles);
      const { data: res } = await this.$http.get("/roles");
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("角色分配列表失败");
      this.rolesList = res.data;
    },
    // 点击了确定按钮分配角色
    async saveRoleInfo() {
      const { data: res } = await this.$http.put(
        `users/${this.roleInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("设置用户角色失败");
      this.$message.success("设置用户角色成功");
      this.rolesDialogVisible = false;
      this.getUserList();
    },
    // 关闭了分配角色弹框
    closeRole() {
      // 关闭弹框以后将id选择框的id重置为空
      // 将要存放要分配角色的信息改为空
      this.selectedRoleId = "";
      this.roleInfo = {};
    },
  },
};
</script>

<style lang='less' scoped>
.lastitem {
  margin-bottom: 0px;
}
</style>